package com.dys.hejiayuncommunity.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.dys.hejiayuncommunity.common.core.exception.BaseException;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: 疾风
 * @ClassName: ExcelUtils
 * @Description: Excel操作工具类
 * @CreateDate: 2024/12/11
 * @Version: v1.0.0
 */
public class ExcelUtils {

    private static final Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 导出excel
     *
     * @param list         数据列表
     * @param entityClass  实体类型
     * @param fileName     导出时的excel名称
     * @param response     响应对象
     * @param exportParams 导出参数(标题、sheet名称、是否创建表头、表格类型)
     */
    public static void exportExcel(List<?> list, Class<?> entityClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        // 1.把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entityClass, list);
        downloadExcel(fileName, response, workbook);
    }

    /**
     * 下载Excel
     *
     * @param fileName 下载时的文件名称
     * @param response 响应对象
     * @param workbook 工作簿里面的excel数据
     */
    private static void downloadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        ServletOutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            // 控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名，文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
            // attachment：弹出对话框让用户下载：disposition-type是以什么方式下载，如attachment为以附件方式下载
            // xls xlm xla xlc xlt xlw
            response.setContentType("application/vnd.ms-excel");
            // response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new BaseException("500", "导出Excel失败,请联系网站管理员!");
        } finally {
            try {
                outputStream.close();
                workbook.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
